// 结果展示页面
import React, { useState, useEffect } from 'react';
import { Layout, Card, Tabs, Typography, Space, Table, List, Tag, Statistic, Row, Col, Divider } from 'antd';
import { mockService } from '../services/mockService';
import type { Job, Model, Metrics } from '../types';
import { formatDateTime } from '../utils/fileUtils';
import * as echarts from 'echarts';

const { Content } = Layout;
const { Title, Text } = Typography;

const ResultsPage: React.FC = () => {
  const [completedJobs, setCompletedJobs] = useState<Job[]>([]);
  const [models, setModels] = useState<Model[]>([]);
  const [activeTab, setActiveTab] = useState<string>('jobs');
  const [chartRef, setChartRef] = useState<HTMLDivElement | null>(null);
  const [chartInstance, setChartInstance] = useState<echarts.ECharts | null>(null);

  // 加载数据
  useEffect(() => {
    loadInitialData();
  }, []);

  // 初始化图表
  useEffect(() => {
    if (chartRef && !chartInstance) {
      const instance = echarts.init(chartRef);
      setChartInstance(instance);
    }

    return () => {
      if (chartInstance) {
        chartInstance.dispose();
      }
    };
  }, [chartRef]);

  // 更新图表
  useEffect(() => {
    if (chartInstance && models.length > 0) {
      updateComparisonChart();
    }
  }, [models, chartInstance]);

  const loadInitialData = async () => {
    try {
      // 加载已完成的作业
      const jobsRes = await mockService.jobs.getAll();
      if (jobsRes.success && jobsRes.data) {
        setCompletedJobs(jobsRes.data.filter(job => job.status === 'completed' && job.metrics));
      }
      // 加载模型
      const modelsRes = await mockService.models.getAll();
      if (modelsRes.success && modelsRes.data) {
        setModels(modelsRes.data);
      }
    } catch (error) {
      console.error('加载数据失败:', error);
    }
  };

  // 更新对比图表
  const updateComparisonChart = () => {
    if (!chartInstance || models.length === 0) return;

    const modelNames = models.map(m => m.name);
    const metrics: string[] = models.length > 0 ? Object.keys(models[0].metrics || {}) : [];
    
    const series = metrics.map(metric => ({
      name: metric,
      type: 'bar',
      data: models.map(m => m.metrics?.[metric as keyof Metrics] || 0),
      emphasis: {
        focus: 'series'
      }
    }));

    const option = {
      title: {
        text: '模型性能对比',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: metrics,
        bottom: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: modelNames,
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        max: 1
      },
      series: series
    };

    chartInstance.setOption(option);
  };

  // 获取最佳指标
  const getBestMetric = (metric: keyof Metrics): { model: Model | null; value: number } => {
    let bestModel: Model | null = null;
    let bestValue = 0;

    models.forEach(model => {
      const value = model.metrics?.[metric] || 0;
      if (value > bestValue) {
        bestValue = value;
        bestModel = model;
      }
    });

    return { model: bestModel, value: bestValue };
  };

  // 渲染作业结果列表
  const renderJobResults = () => (
    <Card title="作业结果列表">
      <Table
        dataSource={completedJobs}
        columns={[
          { title: '作业名称', dataIndex: 'name', key: 'name' },
          { title: '模型类型', dataIndex: ['modelConfig', 'modelType'], key: 'modelType' },
          { 
            title: '准确率', 
            dataIndex: ['metrics', 'accuracy'], 
            key: 'accuracy',
            render: (accuracy) => accuracy ? `${(accuracy * 100).toFixed(2)}%` : '-',
            sorter: (a, b) => (a.metrics?.accuracy || 0) - (b.metrics?.accuracy || 0)
          },
          { 
            title: 'F1分数', 
            dataIndex: ['metrics', 'f1Score'], 
            key: 'f1Score',
            render: (f1) => f1 ? f1.toFixed(4) : '-',
            sorter: (a, b) => (a.metrics?.f1Score || 0) - (b.metrics?.f1Score || 0)
          },
          { 
            title: '完成时间', 
            dataIndex: 'updatedAt', 
            key: 'updatedAt',
            render: (time) => formatDateTime(time)
          }
        ]}
        rowKey="id"
        expandable={{
          expandedRowRender: (job) => (
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <Text strong>评估指标详情：</Text>
                <Space wrap>
                  {job.metrics && Object.entries(job.metrics).map(([key, value]) => (
                    <Tag key={key} color="blue">
                      {key}: {value?.toFixed(4)}
                    </Tag>
                  ))}
                </Space>
              </div>
              <div>
                <Text strong>模型配置：</Text>
                <pre style={{ background: '#f5f5f5', padding: '12px', borderRadius: '4px', overflow: 'auto' }}>
                  {JSON.stringify(job.modelConfig.hyperparameters, null, 2)}
                </pre>
              </div>
            </Space>
          ),
          rowExpandable: () => true,
        }}
      />
    </Card>
  );

  // 渲染模型性能对比
  const renderModelComparison = () => (
    <Card title="模型性能对比">
      {models.length === 0 ? (
        <Text type="secondary">暂无模型数据可对比</Text>
      ) : (
        <Space direction="vertical" style={{ width: '100%' }}>
          <Row gutter={16} style={{ marginBottom: '24px' }}>
            <Col span={6}>
              <Card>
                <Statistic 
                  title="最佳准确率" 
                  value={getBestMetric('accuracy').value * 100} 
                  precision={2}
                  suffix="%"
                />
                <Text type="secondary">
                  模型：{getBestMetric('accuracy').model?.name || '-'}
                </Text>
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic 
                  title="最佳F1分数" 
                  value={getBestMetric('f1Score').value} 
                  precision={4}
                />
                <Text type="secondary">
                  模型：{getBestMetric('f1Score').model?.name || '-'}
                </Text>
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic 
                  title="最佳精确率" 
                  value={getBestMetric('precision').value} 
                  precision={4}
                />
                <Text type="secondary">
                  模型：{getBestMetric('precision').model?.name || '-'}
                </Text>
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic 
                  title="最佳召回率" 
                  value={getBestMetric('recall').value} 
                  precision={4}
                />
                <Text type="secondary">
                  模型：{getBestMetric('recall').model?.name || '-'}
                </Text>
              </Card>
            </Col>
          </Row>
          
          <div style={{ height: '400px', width: '100%' }}>
            <div 
              ref={setChartRef} 
              style={{ height: '100%', width: '100%' }}
            />
          </div>
        </Space>
      )}
    </Card>
  );

  // 渲染最佳模型推荐
  const renderBestModels = () => (
    <Card title="最佳模型推荐">
      {models.length === 0 ? (
        <Text type="secondary">暂无模型数据</Text>
      ) : (
        <List
          dataSource={[
            { type: 'accuracy', title: '准确率最佳' },
            { type: 'f1Score', title: 'F1分数最佳' },
            { type: 'precision', title: '精确率最佳' },
            { type: 'recall', title: '召回率最佳' }
          ]}
          renderItem={(item) => {
            const { model, value } = getBestMetric(item.type as keyof Metrics);
            return (
              <List.Item>
                <List.Item.Meta
                  title={
                    <Space>
                      {item.title}
                      <Tag color="gold">{item.type === 'accuracy' ? `${(value * 100).toFixed(2)}%` : value.toFixed(4)}</Tag>
                    </Space>
                  }
                  description={
                    model ? (
                      <Space direction="vertical">
                        <Text strong>{model.name}</Text>
                        <Text type="secondary">{model.description}</Text>
                        <Text type="secondary">类型：{model.config.modelType}</Text>
                      </Space>
                    ) : (
                      <Text type="secondary">暂无数据</Text>
                    )
                  }
                />
              </List.Item>
            );
          }}
        />
      )}
    </Card>
  );

  return (
    <Layout className="layout">
      <Content style={{ padding: '24px', minHeight: 'calc(100vh - 64px)' }}>
        <Title level={4}>结果展示与模型评估</Title>
        <Text type="secondary">查看模型训练结果、性能指标和对比分析</Text>
        
        <Divider />
        
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <Tabs.TabPane tab="作业结果" key="jobs">
            {renderJobResults()}
          </Tabs.TabPane>
          <Tabs.TabPane tab="模型对比" key="comparison">
            {renderModelComparison()}
          </Tabs.TabPane>
          <Tabs.TabPane tab="最佳模型" key="best">
            {renderBestModels()}
          </Tabs.TabPane>
        </Tabs>
      </Content>
    </Layout>
  );
};

export default ResultsPage;